package com.tubeonfire.model;

import java.util.ArrayList;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import com.tubeonfire.entity.Tuber;

public class TuberModel {

	static PersistenceManager pm = PMF.get().getPersistenceManager();

	public static void initPm() {
		if (pm.isClosed()) {
			pm = PMF.get().getPersistenceManager();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Tuber> all() {
		initPm();
		List<Tuber> result = new ArrayList<Tuber>();
		Query query = pm.newQuery(Tuber.class);
		query.setRange(0, 10);
		result = (List<Tuber>) query.execute();
		return result;
	}

	public static boolean add(Tuber tuber) {
		initPm();
		try {
			pm.makePersistent(tuber);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean addAll(List<Tuber> listTuber) {
		initPm();
		try {
			pm.makePersistentAll(listTuber);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean update(Tuber tuber) {
		initPm();
		pm.makePersistent(tuber);
		return true;
	}

	@SuppressWarnings("unchecked")
	public static Tuber getByEmail(String email) {
		initPm();
		Tuber tuber = null;
		Query query = pm.newQuery(Tuber.class);
		query.setFilter("email==email");
		query.declareParameters("java.lang.String email");
		query.setRange(0, 1);
		List<Tuber> listResult = (List<Tuber>) query.execute(email);
		if (listResult.size() > 0) {
			tuber = listResult.get(0);
		}
		return tuber;
	}

	@SuppressWarnings("unchecked")
	public static boolean isExits(String email) {
		initPm();
		Query query = pm.newQuery(Tuber.class);
		query.setFilter("email==emailPara");
		query.declareParameters("java.lang.String emailPara");
		query.setRange(0, 1);
		List<Tuber> listResult = (List<Tuber>) query.execute(email);
		if (listResult.size() > 0) {
			return true;
		}
		return false;
	}

	public static void closePM() {
		pm.close();
	}

}
